<?php

namespace StudyBuddy\Modules\Observers;

use StudyBuddy\Request;

/**
 * Class to keep records
 * of users who are currently online
 * as well as their current location on
 * the site.
 *
 */
class Online extends \StudyBuddy\Observer {

    /**
     * Title of page currently being viewed
     *
     * @var string
     */
    protected $title = '';

    /**
     * Category of page being viewed
     * Currently we don't have support for categories
     * but this is going to be used in the future
     *
     * @var string
     */
    protected $category = '';

    /**
     * Keywords of page being viewed
     *
     * This is comma-separated list of keywords
     *
     * @var string
     */
    protected $keywords = '';

    public function main() {

        //d('get event: '.$this->eventName);
        //d('$_REQUEST: '.print_r($_REQUEST, 1));
        //d('SERVER: '.print_r($_SERVER, 1));
        $this->title = !empty($this->aInfo['title']) ? $this->aInfo['title'] : '';
        /**
         * This is for the future
         * when we have support for "category" concept
         * a page controller may setup the value of "category"
         * in the template and we may use it to record category
         * into 'ONLINE' collection.
         * This way we may should list of users that are currently
         * viewing items or doing anything in that category.
         *
         */
        $this->category = !empty($this->aInfo['category']) ? $this->aInfo['category'] : '';

        if ('onPageView' === $this->eventName) {

            $this->run();
        }
    }

    /**
     * Update ONLINE_USERS collection
     * @todo exit if useragent is of known Crawler
     * 
     * @todo make logging guests online configurable option via Ini
     *
     */
    protected function run() {
        $Viewer = $this->oRegistry->Viewer;
        $ip = Request::getIP();
        $uid = $Viewer->getUid();
        d('uid: ' . $uid);

        $aData = array(
            'ip' => $ip,
            'i_ts' => time(),
            'ua' => Request::getUserAgent(),
            /* request_viewtags (for example) it could be translated with I18N to show what user is viewing */
            'action' => 'request_' . $this->oRegistry->Request->get('a', 's', 'home'),
            /* REQUEST_URI could be used to make a link to that page */
            'uri' => $_SERVER['REQUEST_URI'],
            'title' => $this->title,
            'category' => $this->category,
            'a_kw' => (!empty($this->aInfo['keywords'])) ? explode(', ', $this->aInfo['keywords']) : array()
        );

        if ($uid > 0) {
            $aData['i_uid'] = $uid;
            $aData['username'] = $Viewer->getDisplayName();
            $aData['avtr'] = $Viewer->getAvatarSrc();
            $aData['profile'] = $Viewer->getProfileUrl();
            $aData['role'] = $Viewer->getRoleId();
            $aData['i_rep'] = $Viewer->getReputation();
        }

        $Mongo = $this->oRegistry->Mongo->getDb();
        $Geo = $this->oRegistry->Geo;


        $func = function() use ($aData, $Mongo, $Geo) {

                    $aGeo = $Geo->getLocation($aData['ip'])->toArray();
                    $aData = $aData + $aGeo;

                    /**
                     * Need unique index uid
                     *
                     */
                    if (array_key_exists('i_uid', $aData)) {
                        $coll = $Mongo->ONLINE;
                        $coll->ensureIndex(array('i_uid' => 1), array('unique' => true));
                        $coll->ensureIndex(array('i_ts' => 1));
                        $coll->update(array('i_uid' => $aData['i_uid']), $aData, array('upsert' => true));
                    } else {
                        /**
                         * For guests the value of ip2long (int)
                         * will be used as uid
                         */
                        $aData['i_uid'] = ip2long($aData['ip']);
                        $coll = $Mongo->GUESTS;
                        $coll->ensureIndex(array('i_uid' => 1), array('unique' => true));
                        $coll->ensureIndex(array('i_ts' => 1));
                        $coll->update(array('ip' => $aData['ip']), $aData, array('upsert' => true));
                    }

                    /**
                     * Remove old records
                     * Cleanup runs 10% of requests
                     * removes records older than 24 hours
                     */
                    if (1 === rand(0, 10)) {
                        $offset = time() - (60 * 60 * 24);
                        $coll->remove(array('i_ts' => array('$lt' => $offset)));
                    }
                };

        \StudyBuddy\runLater($func);
    }

}
